package game.module.nn.processor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;
import game.module.hall.logic.CheatManager;
import game.module.nn.bean.NnRoom;
import game.module.nn.logic.NnDataManager;
import lion.common.MsgCodeAnn;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lua.LuaMessageLogin.S2ErrorCode;
import lua.LuaMessageNn.C2SNNJoinRoomCheck;
import lua.LuaMessageNn.S2CNNJoinRoomCheck;

@MsgCodeAnn(msgcode = C2SNNJoinRoomCheck.id, accessLimit = 500)
public class NnJoinRoomCheckProcessor extends PlayingRoleMsgProcessor {

	private static Logger logger = LoggerFactory.getLogger(NnJoinRoomCheckProcessor.class);

	@Override
	public void process(PlayingRole hero, RequestMessageRaw request) throws Exception {
		C2SNNJoinRoomCheck reqMsg = C2SNNJoinRoomCheck.parse(request);
		String room_id = reqMsg.room_id;
		int playerId = hero.getId();
		logger.info("nn join room check,playeyId={},room_id={}", playerId, room_id);
		// 是否在房间中
		boolean isInRoom = NnDataManager.getInstance().isPlayerInRoom(playerId);
		if (isInRoom) {
			S2ErrorCode respMsg = new S2ErrorCode(102);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		// is fang not exist
		if (!NnDataManager.getInstance().checkRoomExist(room_id)) {
			S2ErrorCode respMsg = new S2ErrorCode(104);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		final NnRoom nnRoom = NnDataManager.getInstance().getNnRoom(room_id);
		int fangka = hero.getPlayerBean().getFang_ka();
		int fangka_cost = nnRoom.getRoomfee();
		if (nnRoom.getRoomFeeType() == 2 && fangka < fangka_cost)// 赢家收费
		{
			S2ErrorCode respMsg = new S2ErrorCode(103);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		if (nnRoom.getRoomFeeType() == 1 && fangka < fangka_cost / 2) {// AA
			S2ErrorCode respMsg = new S2ErrorCode(103);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		if (nnRoom.getIs_jindou() == 1 && hero.getPlayerBean().getJin_dou() < nnRoom.getJindou() * nnRoom.getRoundCount() * 40) {// 金豆房间
			S2ErrorCode respMsg = new S2ErrorCode(133);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		// 人数已满
		if (nnRoom.getPlayerList().size() >= 5) {
			S2ErrorCode respMsg = new S2ErrorCode(105);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}

		if (CheatManager.getInstance().checkCheatAndPush(nnRoom.getPrevent_cheat(), nnRoom.getIps(), hero)) {
			return;
		}
		// ret
		S2CNNJoinRoomCheck respMsg = new S2CNNJoinRoomCheck();
		hero.writeAndFlush(respMsg.build(hero.alloc()));
	}

	@Override
	public void processProto(PlayingRole playingRole, RequestProtoMessage request) throws Exception {
		// null
	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {
		// null
	}

}
